package com.open1111.realm;

import com.open1111.entity.Manager;
import com.open1111.service.ManagerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * 自定义realm
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private ManagerService managerService;

    /**
     * 为当前登录的用户授予角色和权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 验证当前登录的用户
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        Manager manager = managerService.getByUserName(userName);

        if (null != manager) {
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", manager);

            AuthenticationInfo authenticationInfo  = new SimpleAuthenticationInfo(manager.getUserName(), manager.getPassword(), "xxx");
            return authenticationInfo;
        } else {
            return null;
        }
    }
}
